use actix_web::{HttpRequest, delete, get, post, put, web};

use log::{info, trace};
use rbase::{
    define::{ApiError, ApiResponse},
    id_utils::{opt_id2str, opt_str2id},
};
use rbase_iam::rest_api::service::auth_check::get_user_from_request;
use serde::{Deserialize, Serialize};

use crate::{
    db::entities::scheduler::Model,
    rest_api::service::srv_scheduler::{self},
};

use anyhow::Result;
use rbase::id_utils::{id2str, str2id};

#[derive(Clone, Debug, Deserialize)]
pub struct CreateParams {
    pub name: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct UpdateParams {
    pub name: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct ImportParams {
    pub name: Option<String>,
    pub category_id: Option<String>,
    pub subject_id: Option<String>,

    pub ids: Option<Vec<String>>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Scheduler {
    pub id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_at: Option<i64>,
}

impl Scheduler {
    pub fn from_model(entity: &Model) -> Self {
        Scheduler {
            id: id2str(entity.id),
            name: entity.name.clone(),
            created_at: entity.created_at,
            modified_at: entity.modified_at,
            owner_id: opt_id2str(&entity.owner_id),
        }
    }

    pub fn to_model(&self) -> Result<Model> {
        Ok(Model {
            id: str2id(&self.id)?,
            name: self.name.clone(),
            created_at: self.created_at,
            modified_at: self.modified_at,
            owner_id: opt_str2id(&self.owner_id)?,
        })
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Dashboard {
    pub knowledge_total: i64,
    pub knowledge_mastered: i64,
    pub knowledge_need_learned_today: i64,
    pub knowledge_learning: i64,
    pub task_total: i64,
    pub task_completed: i64,
}

#[derive(Deserialize, Debug)]
pub struct SearchParams {
    #[serde(default)]
    pub name: Option<String>,

    #[serde(default)]
    pub offset: Option<u64>,

    #[serde(default)]
    pub limit: Option<u64>,

    #[serde(default)]
    pub order_by: Option<String>,

    #[serde(default)]
    pub order: Option<String>,
}

#[get("/api/v1/schedulers")]
async fn list_schedulers(req: HttpRequest, query_params: web::Query<SearchParams>) -> Result<ApiResponse, ApiError> {
    let scheduler_search_params = query_params.into_inner();
    trace!("list_schedulers query: {:?}", scheduler_search_params);
    let user_token = get_user_from_request(&req)?;
    let (schedulers, total) = srv_scheduler::search(&user_token, &scheduler_search_params).await?;
    Ok(ApiResponse::datas(schedulers, total))
}

#[post("/api/v1/schedulers")]
async fn create_scheduler(req: HttpRequest, req_body: String) -> Result<ApiResponse, ApiError> {
    trace!("create_scheduler body: {}", req_body);
    let user_token = get_user_from_request(&req)?;
    let new_scheduler: CreateParams = serde_json::from_str(&req_body)?;

    let scheduler = srv_scheduler::create_scheduler(&user_token, &new_scheduler).await?;
    Ok(ApiResponse::data(scheduler))
}

#[get("/api/v1/schedulers/{id}")]
async fn get_scheduler(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    let scheduler_id = path_params.into_inner();
    trace!("get_scheduler path: {:?}", scheduler_id);
    let user_token = get_user_from_request(&req)?;
    let result = srv_scheduler::find_scheduler_by_id(&user_token, &scheduler_id).await?;
    Ok(ApiResponse::data(result))
}

#[delete("/api/v1/schedulers/{id}")]
async fn delete_scheduler(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("delete_scheduler path: {:?}", path_params);
    let user_token = get_user_from_request(&req)?;
    let scheduler_id = path_params.into_inner();
    srv_scheduler::delete_scheduler_by_id(&user_token, &scheduler_id).await?;
    Ok(ApiResponse::success())
}

#[put("/api/v1/schedulers/{id}")]
async fn update_scheduler(req: HttpRequest, req_body: String, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("update_scheduler path: {:?}, body: {}", path_params, req_body);
    let user_token = get_user_from_request(&req)?;
    let new_scheduler: UpdateParams = serde_json::from_str(&req_body)?;

    let scheduler_id = path_params.into_inner();
    srv_scheduler::update_scheduler_by_id(&user_token, &scheduler_id, &new_scheduler).await?;
    Ok(ApiResponse::success())
}

#[post("/api/v1/schedulers/{id}/knowledge")]
async fn import_knowledge_to_scheduler(req: HttpRequest, req_body: String, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("import_knowledge_to_scheduler path: {:?}, body: {}", path_params, req_body);
    let user_token = get_user_from_request(&req)?;

    let import_params: ImportParams = serde_json::from_str(&req_body)?;

    let scheduler_id = path_params.into_inner();
    srv_scheduler::import_knowledge_to_scheduler(&user_token, &scheduler_id, &import_params).await?;
    Ok(ApiResponse::success())
}

#[get("/api/v1/schedulers/{id}/dashboard")]
async fn get_scheduler_dashboard(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("get_scheduler_dashboard path: {:?}", path_params);
    let user_token = get_user_from_request(&req)?;

    let scheduler_id = path_params.into_inner();
    let result = srv_scheduler::get_scheduler_dashboard(&user_token, &scheduler_id).await?;
    Ok(ApiResponse::data(result))
}

pub fn config(cfg: &mut web::ServiceConfig) {
    info!("Configuring scheduler APIs");
    cfg.service(list_schedulers);
    cfg.service(create_scheduler);
    cfg.service(get_scheduler);
    cfg.service(delete_scheduler);
    cfg.service(update_scheduler);
    cfg.service(import_knowledge_to_scheduler);
    cfg.service(get_scheduler_dashboard);
}
